package com.web.servlet;


import com.web.JBDCUtils;
import com.web.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/insertStudent")
public class InsertStudentServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String name = req.getParameter("name");
        String ageStr = req.getParameter("age");
        String gender = req.getParameter("gender");
        if (name != null && !name.isEmpty() && ageStr != null && !ageStr.isEmpty() && gender != null && !gender.isEmpty()) {
            try {
                int age = Integer.parseInt(ageStr);
                int rows = JBDCUtils.update("INSERT INTO students (name, age, gender) VALUES (?, ?, ?)", name, age, gender);
                if (rows > 0) {
                    out.println("学生插入成功");
                } else {
                    out.println("学生插入失败");
                }
            } catch (NumberFormatException e) {
                out.println("输入的年龄不是有效的整数");
            }
        } else {
            out.println("请提供完整的学生信息");
        }
    }
}